<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE简单测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        button:hover {
            background: #0056b3;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .status {
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
            font-weight: bold;
        }
        .status.connected {
            background: #d4edda;
            color: #155724;
        }
        .status.disconnected {
            background: #f8d7da;
            color: #721c24;
        }
        .messages {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            background: #f9f9f9;
            border-radius: 4px;
        }
        .message {
            margin-bottom: 10px;
            padding: 8px;
            background: white;
            border-radius: 4px;
            border-left: 3px solid #007bff;
        }
        .message.error {
            border-left-color: #dc3545;
        }
        .message.success {
            border-left-color: #28a745;
        }
        .timestamp {
            font-size: 12px;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>SSE简单测试</h1>
        
        <div id="status" class="status disconnected">未连接</div>
        
        <div class="form-group">
            <label for="baseUrl">服务端地址:</label>
            <input type="text" id="baseUrl" value="http://localhost:8080">
        </div>
        
        <div class="form-group">
            <label for="token">Token:</label>
            <input type="text" id="token" value="test-token-123">
        </div>
        
        <div class="form-group">
            <label for="userId">用户ID:</label>
            <input type="number" id="userId" value="1">
        </div>
        
        <button id="connectBtn">连接</button>
        <button id="disconnectBtn" disabled>断开</button>
        <button id="sendBtn" disabled>发送测试消息</button>
        
        <h3>消息记录:</h3>
        <div id="messages" class="messages">
            <div class="message">
                <div class="timestamp">等待连接...</div>
                <div>请点击连接按钮开始测试</div>
            </div>
        </div>
    </div>

    <script>
        let eventSource = null;
        let isConnected = false;
        
        const statusEl = document.getElementById('status');
        const baseUrlEl = document.getElementById('baseUrl');
        const tokenEl = document.getElementById('token');
        const userIdEl = document.getElementById('userId');
        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const sendBtn = document.getElementById('sendBtn');
        const messagesEl = document.getElementById('messages');
        
        function updateStatus(connected, text) {
            isConnected = connected;
            statusEl.className = `status ${connected ? 'connected' : 'disconnected'}`;
            statusEl.textContent = text;
            
            connectBtn.disabled = connected;
            disconnectBtn.disabled = !connected;
            sendBtn.disabled = !connected;
        }
        
        function addMessage(type, text) {
            const messageEl = document.createElement('div');
            messageEl.className = `message ${type}`;
            
            const timestamp = new Date().toLocaleTimeString();
            messageEl.innerHTML = `
                <div class="timestamp">${timestamp}</div>
                <div>${text}</div>
            `;
            
            messagesEl.appendChild(messageEl);
            messagesEl.scrollTop = messagesEl.scrollHeight;
        }
        
        function connect() {
            const baseUrl = baseUrlEl.value.trim();
            const token = tokenEl.value.trim();
            const userId = userIdEl.value.trim();
            
            if (!baseUrl || !token || !userId) {
                alert('请填写完整信息');
                return;
            }
            
            try {
                // 注意：EventSource不支持自定义headers，这里需要服务端支持从URL参数获取token
                const url = `${baseUrl}/api/client/sse/connect?token=${encodeURIComponent(token)}&userId=${userId}`;
                
                eventSource = new EventSource(url);
                
                eventSource.onopen = function(event) {
                    updateStatus(true, '已连接');
                    addMessage('success', 'SSE连接已建立');
                };
                
                eventSource.onerror = function(event) {
                    updateStatus(false, '连接错误');
                    addMessage('error', 'SSE连接错误');
                    if (eventSource) {
                        eventSource.close();
                        eventSource = null;
                    }
                };
                
                eventSource.onmessage = function(event) {
                    addMessage('', `收到消息: ${event.data}`);
                };
                
                // 监听自定义事件
                eventSource.addEventListener('connected', function(event) {
                    addMessage('success', `连接成功: ${event.data}`);
                });
                
                eventSource.addEventListener('notification', function(event) {
                    addMessage('', `通知: ${event.data}`);
                });
                
                eventSource.addEventListener('error', function(event) {
                    addMessage('error', `错误: ${event.data}`);
                });
                
            } catch (error) {
                addMessage('error', `连接失败: ${error.message}`);
                updateStatus(false, '连接失败');
            }
        }
        
        function disconnect() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }
            updateStatus(false, '已断开');
            addMessage('', 'SSE连接已断开');
        }
        
        async function sendTestMessage() {
            const baseUrl = baseUrlEl.value.trim();
            const token = tokenEl.value.trim();
            const userId = userIdEl.value.trim();
            
            try {
                const testData = {
                    title: '测试消息',
                    content: '这是一条来自前端的测试消息',
                    timestamp: new Date().toISOString()
                };
                
                const response = await fetch(`${baseUrl}/api/client/sse/send/${userId}?eventName=notification`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'token': token
                    },
                    body: JSON.stringify(testData)
                });
                
                if (response.ok) {
                    const result = await response.json();
                    addMessage('success', `消息发送成功: ${JSON.stringify(result)}`);
                } else {
                    throw new Error(`HTTP ${response.status}`);
                }
            } catch (error) {
                addMessage('error', `消息发送失败: ${error.message}`);
            }
        }
        
        connectBtn.addEventListener('click', connect);
        disconnectBtn.addEventListener('click', disconnect);
        sendBtn.addEventListener('click', sendTestMessage);
    </script>
</body>
</html> 